package com.kaluli.project.service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kaluli.project.domain.entity.AbroadVO;
import com.kaluli.project.domain.entity.KllMainOrderDetail;
import com.kaluli.project.domain.entity.KllOrderLogistics;
import com.kaluli.project.domain.repository.KllOrderLogisticsRepository;
import com.kaluli.project.utils.DateUtil;

@Service
@Configuration
@Transactional
@PropertySource({"classpath:thridsystem.properties"})
public class KllOrderLogisticsService {
	
	static Logger log = Logger.getLogger(KllOrderLogisticsService.class.getName());
	
	@Autowired
	private Environment env;
	
	@Autowired
	private KllOrderLogisticsRepository kllOrderLogisticsRepository;
	
	
	@Autowired
	private KllMainOrderDetailService kllMainOrderDetailService;
	
	@Transactional(rollbackOn = {RuntimeException.class, Exception.class})
	public int updateOrderLogistics(JSONObject ja,String orderNumber){
		int flag = 0 ;
		KllOrderLogistics kol = new KllOrderLogistics();
		String orderid = ja.getString("orderId");
		String wayBillNo = ja.getString("wayBillNo");
		String logisticsname = ja.getString("logisticsname");
		String logisticsid = ja.getString("logisticsid");
		String notes = ja.getString("notes");
		
		kol.setOrderNumber(orderid);
		kol.setExpressNumber(wayBillNo);
		kol.setExcompany(env.getProperty("zz.domestic_express_name"));
		//kol.set
		
		JSONArray logisticsInfos = ja.getJSONArray("logisticsInfos");
		
		
		return flag;
	}
	
	/**
	 * 更新物流单号
	 * @param expressNumber
	 * @param orderNumber
	 * @return
	 */
	@Transactional(rollbackOn = {RuntimeException.class, Exception.class})
	public void updateExpressNum(String expressNumber,String orderNumber){
		log.info(orderNumber+"订单物流回写,物流单号="+expressNumber);
		kllOrderLogisticsRepository.updateExpressNum(expressNumber, orderNumber);
		
	}
	
	/**
	 * 同步国际段物流信息
	 * @param abroad
	 * @param orderNumber
	 * @return
	 */
	@Transactional(rollbackOn = {RuntimeException.class, Exception.class})
	public void updateAbroad(String abroad,String orderNumber){
		
		log.info("物流写入信息:"+abroad);
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		AbroadVO vo = new AbroadVO();
		vo.setContext(abroad);
		vo.setTime(sf.format(new Date()));
		vo.setFtime(sf.format(new Date()));
		vo.setAreaCode("000000000000");//虚拟的数据
		vo.setStatus("在途");
		
	    KllOrderLogistics logistics = 	kllOrderLogisticsRepository.findByOrderNumber(orderNumber);
	    if(logistics != null){
	    	String road = logistics.getAbroad();
	    	String json ="";
	    	List<AbroadVO> list = new ArrayList<>();
	    	if(StringUtils.isNotBlank(road)){
	    		list = JSON.parseArray(road, AbroadVO.class);
	    		list.add(vo);
	    	}else{
	    		list.add(vo);
	    	}
	    	json = JSON.toJSONString(list);
	    	kllOrderLogisticsRepository.updateAbroad(json, orderNumber);
	    }else{
	    	log.info("没有找到该订单的物流信息:"+orderNumber);
	    }
		
		
	}
	
	public void optLogistic(String type) {
		
		List<KllMainOrderDetail> detail = kllMainOrderDetailService.getListByDetail();
		for(KllMainOrderDetail d:detail){
			updateAbroadSR(d.getOrderNumber(), type);
			
		}

	}
	
	
	/**
	 * 同步速尔国际段物流信息
	 * @param abroad
	 * @param orderNumber
	 * @return
	 */
	@Transactional(rollbackOn = {RuntimeException.class, Exception.class})
	public void updateAbroadSR(String orderNumber,String type){
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		AbroadVO vo = new AbroadVO();
		
		vo.setTime(sf.format(new Date()));
		vo.setFtime(sf.format(new Date()));
		vo.setAreaCode("000000000000");//虚拟的数据
		vo.setStatus("在途");
		
	    KllOrderLogistics logistics = 	kllOrderLogisticsRepository.findByOrderNumber(orderNumber);
	    String json ="";
	    if(logistics != null){
	    	String road = logistics.getAbroad();
	    	
	    	List<AbroadVO> list = new ArrayList<>();
	    	list = JSON.parseArray(road, AbroadVO.class);
	    	//判断速尔物流过程
	    	int status = logistics.getStatus();
	    	if(status == 1 && StringUtils.isNotBlank(type)){
	    		vo.setContext("您的订单已经开始拣货打包");
	    		list.add(vo);
	    		status =2;
	    		json = JSON.toJSONString(list);
		    	kllOrderLogisticsRepository.updateLogistic(json, orderNumber, status);
		    	return;
	    	}
	    	if(status == 2){
	    		//判断是否到了三个小时
	    		Date time = logistics.getUpdatedAt();
	    		if(time.before(DateUtil.beforeThrToNowDate())){
	    			//录入物流信息3
	    			vo.setContext("您的订单已打包完成，等待香港速尔收件");
		    		list.add(vo);
		    		status=3;
		    		json = JSON.toJSONString(list);
			    	kllOrderLogisticsRepository.updateLogistic(json, orderNumber, status);
			    	return;
	    		}
	    		
	    	}
	    	
	    }else{
	    	//初始化物流数据
	    	saveLogistic(orderNumber);
	    	
	    }
	   
		
	}
	
	
	public void saveLogistic(String orderNumber){
		// 初始化物流信息记录
		KllOrderLogistics logistics = new KllOrderLogistics();
		logistics.setOrderNumber(orderNumber);
		logistics.setToCity("");
		SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// 物流写入 订单提交成功，等待海关清关
		AbroadVO vo = new AbroadVO();
		vo.setContext("香港仓库已经收到了您的信息");
		vo.setTime(sf.format(new Date()));
		vo.setFtime(sf.format(new Date()));
		vo.setAreaCode("000000000000");// 虚拟的数据
		vo.setStatus("揽收");
		List<AbroadVO> list = new ArrayList<>();
		list.add(vo);
		String json = JSON.toJSONString(list);
		logistics.setAbroad(json);
		logistics.setCreatedAt(new Timestamp(System.currentTimeMillis()));
		logistics.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
		logistics.setDomesticStatus("abort");
		logistics.setStatus(1);
		kllOrderLogisticsRepository.save(logistics);
	}
	
	
}
